import { ld } from '@/llmDialog'
import type { LDEvents, LDFile, LDStateReactive } from '@/llmDialog/types'
import { nanoid } from 'nanoid'

export default function useHandleFile(
  state: LDStateReactive,
  {
    uploadFiles: emitUploadFiles,
    deleteFile: emitDeleteFile,
    clearFiles: emitClearFiles,
  }: LDEvents,
) {
  // 上传文件
  function uploadFile(file: File) {
    state.files.push(ld.createFile(file))
  }

  // 上传多个文件
  function uploadFiles(files: FileList) {
    Array.from(files).forEach((file) => uploadFile(file))
    // 触发上传文件事件
    emitUploadFiles(files)
  }

  // 删除文件
  function deleteFile(fileId: string) {
    const file = state.files.find((f) => f.id === fileId)?.file
    const index = state.files.findIndex((f) => f.file === file)
    if (index >= 0) {
      state.files.splice(index, 1)
    }
    // 触发删除文件事件
    emitDeleteFile(file as File)
  }

  // 清空文件
  function clearFiles() {
    const files = state.files.map((f) => f.file) as File[]
    state.files.splice(0, state.files.length)
    // 触发清空文件事件
    emitClearFiles(files)
  }

  return {
    uploadFile,
    uploadFiles,
    deleteFile,
    clearFiles,
  }
}
